import React, { Suspense } from 'react'
import { useLoader } from '@react-three/fiber'
import { 
  PivotControls, 
  useProgress, 
  Html, 
 } from '@react-three/drei'
import { OBJLoader, MTLLoader } from 'three/addons'

export function LoadObjModel({
  modelUrl = '/city/city1-with-mat.obj', 
  mtlUrl = '/city/city1-with-mat.mtl',
  hasPivot = false
}) {

  const mtl = useLoader(MTLLoader, mtlUrl);
  const obj = useLoader(OBJLoader, modelUrl, loader => {
    mtl.preload();
    loader.setMaterials(mtl)
  });
  return <Suspense fallback={<Loader />}>
    {
      hasPivot
        ? <PivotControls anchor={[.2, .5, 0]}>
        <primitive object={obj} scale={0.01} ></primitive>
      </PivotControls>
        : <primitive object={obj} scale={0.01} ></primitive>
    }
  </Suspense>  
}

function Loader() {
  const { progress } = useProgress();
  return <Html>
    <h1 style={{color: 'white', 'fontSize': '30px'}}>
      {progress}% loaded
    </h1>
  </Html>
}